package com.xzkydz.all_sensor.activity;

import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;

import com.serialport.ComAssistant.MyFunc;
import com.serialport.ComAssistant.SerialHelper;
import com.serialport.bean.ComBean;
import com.serialport.bean.ShowInf;
import com.xzkydz.all_sensor.adapter.UnitAdapter;
import com.xzkydz.all_sensor.allsensor.R;

import java.io.IOException;
import java.security.InvalidParameterException;
import java.text.DecimalFormat;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import android_serialport_api.SerialPortFinder;


public class Main2Activity extends AppCompatActivity {

    SerialControl ComA;
    DispQueueThread DispQueue;
    SerialPortFinder mSerialPortFinder;//串口设备搜索
    private ShowInf showInf;
    private int Index1 ,Index2 ,Index3 ,Index4 ,Index5 ,Index6 ,Index7 ,Index8 ,Index9 ,Index10 ;
    private List<ShowInf> list;
    private UnitAdapter adapter;
    private ShowInf showInf_init;
    private EditText textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main2);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("锚杆测力计");
        setSupportActionBar(toolbar);
        textView = (EditText)findViewById(R.id.tv_show);
//        ListView  listView  = (ListView)findViewById(R.id.lv_show);
//
//        showInf = new ShowInf("- -","- -","- -","- -");
//
//        showInf_init = new ShowInf("- -","- -","- -","- -");
//        list = new ArrayList<ShowInf>();
//        ShowInf  showInf1  = new ShowInf("温度","MPa","KN","电压");
//        list.add(showInf1);
//        for (int i =0 ;i<10;i++){
//            list.add(showInf);
//        }
//
//        adapter = new UnitAdapter(Main2Activity.this, list);
//        listView.setAdapter(adapter);
        //串口控制
        ComA = new SerialControl();
        DispQueue = new DispQueueThread();
        DispQueue.start();
        setControls();
    }


    //----------------------------------------------------刷新显示线程
    private class DispQueueThread extends Thread {
        private Queue<ComBean> QueueList = new LinkedList<ComBean>();

        @Override
        public void run() {
            super.run();
            while (!isInterrupted()) {
                final ComBean ComData;
                while ((ComData = QueueList.poll()) != null) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            DispRecData(ComData);
                        }
                    });
                    try {
                        Thread.sleep(500);//显示性能高的话，可以把此数值调小。
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }
        public synchronized void AddQueue(ComBean ComData) {
            QueueList.add(ComData);
        }
    }


    //----------------------------------------------------显示接收数据
    private void DispRecData(ComBean ComRecData) {
        StringBuilder sMsg = new StringBuilder();
        DecimalFormat df2 = new DecimalFormat("####00.00");
        DecimalFormat df3 = new DecimalFormat("####00.000");
        DecimalFormat df4 = new DecimalFormat("####00.0000");

        sMsg.append(" —————————————————————————————————————————————");
        sMsg.append(MyFunc.ByteArrToHex(ComRecData.bRec));
        String noString = "";
        String haveString = "";
        String res = "";


        for (int i = 0; i < ComRecData.bRec.length; i++) {
            res = res+MyFunc.Byte2Hex(ComRecData.bRec[i])+"     "+ComRecData.bRec[i]+" \n";
        }
//
//        for (int i = 0; i <ComRecData.bRec.length-1 ; i+=2) {
//            noString = noString +MyFunc.Byte2Hex(ComRecData.bRec[i])+MyFunc.Byte2Hex(ComRecData.bRec[i+1])+ "  =   "  + MyFunc.noFH(ComRecData.bRec[i],ComRecData.bRec[i+1])+"       "+MyFunc.twobyteToint_(ComRecData.bRec[i],ComRecData.bRec[i+1])+" \n ";
//        }
        for (int i = 0; i <ComRecData.bRec.length-1 ; i+=2) {
            String hex = MyFunc.Byte2Hex(ComRecData.bRec[i])+MyFunc.Byte2Hex(ComRecData.bRec[i+1]);
            haveString = haveString +hex+ " ---->>> "  + MyFunc.haveFH(ComRecData.bRec[i],ComRecData.bRec[i+1])+"       "+MyFunc.twobyteToint(ComRecData.bRec[i],ComRecData.bRec[i+1])+"\n";
        }
        sMsg.append("直接转换：\n" +res);
//        sMsg.append("无符号数计算：\n" +noString);
        sMsg.append("有符号数计算：\n" +haveString);
        sMsg.append("\r\n");
        textView.append(sMsg);


//        boolean showLineNum = false;  // 是否显示条数
//        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd   HH-mm-ss", Locale.getDefault());
//        int LEIXING = ComRecData.bRec[3];
//
//        String pattern = "#0.00";//格式代码，".000"代表保留三位小数，是0的输出0
//        DecimalFormat formatter = new DecimalFormat();
//        formatter.applyPattern(pattern);
//        Index1 +=1;
//        Index2 +=1;
//        Index3 +=1;
//        Index4 +=1;
//        Index5 +=1;
//        Index6 +=1;
//        Index7 +=1;
//        Index8 +=1;
//        Index9 +=1;
//        Index10 +=1;
//
//
//        if (LEIXING==22){
//            int sensorNumber =  MyFunc.HexToInt( MyFunc.ByteArrToHex(ComRecData.bRec, 8, 9));
//            switch (sensorNumber){
//                case 1:
//                    Index1 =0;
//                    break;
//                case 2:
//                    Index2 =0;
//                    break;
//                case 3:
//                    Index3 =0;
//                    break;
//                case 4:
//                    Index4 =0;
//                    break;
//                case 5:
//                    Index5 =0;
//                    break;
//                case 6:
//                    Index6 =0;
//                    break;
//                case 7:
//                    Index7 =0;
//                    break;
//                case 8:
//                    Index8 =0;
//                    break;
//                case 9:
//                    Index9 =0;
//                    break;
//                case 10:
//                    Index10 =0;
//                    break;
//                default:
//                    break;
//            }
//
//            if (Index1>=15)   list.set(1,showInf_init);
//            if (Index2>=15)   list.set(2,showInf_init);
//            if (Index3>=15)   list.set(3,showInf_init);
//            if (Index4>=15)   list.set(4,showInf_init);
//            if (Index5>=15)   list.set(5,showInf_init);
//            if (Index6>=15)   list.set(6,showInf_init);
//            if (Index7>=15)   list.set(7,showInf_init);
//            if (Index8>=15)   list.set(8,showInf_init);
//            if (Index9>=15)   list.set(9,showInf_init);
//            if (Index10>=15)  list.set(10,showInf_init);
//
//            String yaliString_Mpa =null;
//            String yaliString_KN =null;
//            String wenduString = null;
//            String dianliangString = null;
//            // y = 6.9427x + 1.3755
//            float  fl  = (float) MyFunc.HexToInt(MyFunc.ByteArrToHex(ComRecData.bRec, 9, 11)) /100;
//            yaliString_Mpa = formatter.format( (float)fl);
//            yaliString_KN =  formatter.format( (float)6.9427*fl+1.3755);
//            wenduString = formatter.format( (float) MyFunc.HexToInt(MyFunc.ByteArrToHex(ComRecData.bRec, 11, 13)) /100);
//            dianliangString = formatter.format( (float) MyFunc.HexToInt(MyFunc.ByteArrToHex(ComRecData.bRec,13, 15)) /1000);
//
//            showInf.setString(wenduString);
//            showInf.setString1(yaliString_Mpa);
//            showInf.setString2(yaliString_KN);
//            showInf.setString3(dianliangString);
//
//            list.set(sensorNumber,showInf);
//
//            adapter.notifyDataSetChanged();
//        }






//
//        if (showLineNum) {
//            // TODO: 2016/8/25 设置是否积累刷新
//            if (showStyle )  mShowInf.setText("");
//            if (mTogglButton.isChecked()){sMsg.append(code);
//                sMsg.append("\r\n");}
//            sMsg.append("\r\n");
//            sMsg.append(resultInf);
//            sMsg.append("\r\n");
//            sMsg.append(" —————————————————————————————————————————————");
//            sMsg.append("\r\n");
//            mShowInf.append(sMsg);
//            mShowLine.setText((dataNum += 1) + "条");
//        }


    }




    // ----------------------------------------------------设置串口
    private void setControls() {
        mSerialPortFinder = new SerialPortFinder();
        String[] entryValues = mSerialPortFinder.getAllDevicesPath(); // 获取所有的串口
        for (int i = 0; i < entryValues.length; i++) {
            System.out.println(entryValues[i]);
        }
        ComA.setPort(entryValues[6]);

        ComA.setBaudRate("9600");
        OpenComPort(ComA);
    }

    //----------------------------------------------------串口控制类
    private class SerialControl extends SerialHelper {

        public SerialControl() {
        }

        protected void onDataReceived(ComBean ComRecData) {
            // TODO Auto-generated method stub
            DispQueue.AddQueue(ComRecData); //线程定时刷新显示(推荐)
        }
    }

    //----------------------------------------------------串口发送
    public void sendPortData(String sOut) {
        if (ComA != null && ComA.isOpen()) {
            ComA.sendHex(sOut);
        }
    }

    //----------------------------------------------------关闭串口
    private void CloseComPort(SerialHelper ComPort) {
        if (ComPort != null) {
            ComPort.stopSend();
            ComPort.close();
        }
    }

    //----------------------------------------------------打开串口
    private void OpenComPort(SerialHelper ComPort) {
        try {
            ComPort.open();
        } catch (SecurityException e) {
            ShowMessage("打开串口失败:没有串口读/写权限!");
        } catch (IOException e) {
            ShowMessage("打开串口失败:未知错误!");
        } catch (InvalidParameterException e) {
            ShowMessage("打开串口失败:参数错误!");
        }
    }

    //
    public void ShowInf(String sMsg) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(sMsg);
//        mShowInf.append(stringBuilder);
    }
    //------------------------------------------显示消息
    private void ShowMessage(String sMsg) {
        Toast.makeText(this, sMsg, Toast.LENGTH_SHORT).show();
    }


    //屏蔽home
    @Override
    public void onAttachedToWindow() {
        try {
            int version = Build.VERSION.SDK_INT;
            if (version >= 15) {
                this.getWindow().setFlags(0x80000000, 0x80000000);
            } else {
                this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
            }
            super.onAttachedToWindow();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        System.out.println("Page01 -->onKeyDown: keyCode: " + keyCode);
        if (KeyEvent.KEYCODE_HOME == keyCode) {
            System.out.println("HOME has been pressed yet ...");
            // android.os.Process.killProcess(android.os.Process.myPid());
            Toast.makeText(getApplicationContext(), "HOME 键已被禁用...",
                    Toast.LENGTH_SHORT).show();
        }else if (KeyEvent.KEYCODE_BACK ==keyCode){
            dialog();

        }
        return super.onKeyDown(keyCode, event); // 不会回到 home 页面
    }



    protected void dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(Main2Activity.this);
        builder.setMessage("确认退出吗？");
        builder.setTitle("提示");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Main2Activity.this.finish();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }


}
